package com.lanxiao.cloud.modules.dict.application.assembler;

import com.lanxiao.cloud.modules.dict.application.dto.DictBaseDto;
import com.lanxiao.cloud.modules.dict.application.dto.DictCmdAdd;
import com.lanxiao.cloud.modules.dict.application.dto.DictCmdUpdate;
import com.lanxiao.cloud.modules.dict.application.dto.DictDto;
import com.lanxiao.cloud.modules.dict.domain.model.Dict;
import com.lanxiao.cloud.user.api.fill.BaseDtoFillHandleFactory;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-09-26
 */
@Component
public class DictAssembler {

  private final BaseDtoFillHandleFactory<Long> fillHandleFactory;

  public DictAssembler(
      BaseDtoFillHandleFactory<Long> fillHandleFactory) {
    this.fillHandleFactory = fillHandleFactory;
  }


  public Dict toDict(DictCmdAdd cmdAdd) {
    return DictConverter.INSTANCE.toDict(cmdAdd);
  }

  public Dict toDict(Long id, DictCmdUpdate cmdUpdate) {
    Dict dict = DictConverter.INSTANCE.toDict(cmdUpdate);
    dict.setId(id);
    return dict;
  }

  public Map<String, List<DictBaseDto>> toDictBaseDto(List<Dict> list) {
    return DictConverter.INSTANCE.toDictBaseDto(list).stream().collect(Collectors.groupingBy(DictBaseDto::getType));
  }

  public List<DictDto> toDictDto(List<Dict> list) {
    List<DictDto> dictDtos = DictConverter.INSTANCE.toDictDto(list);
    fillHandleFactory.fillHandle(dictDtos);
    return dictDtos;
  }

  @Mapper
  public interface DictConverter {

    DictConverter INSTANCE = Mappers.getMapper(DictConverter.class);

    @Mappings({
        @Mapping(source = "createBy", target = "createUser.id"),
        @Mapping(source = "updateBy",target = "updateUser.id")
    })
    DictDto toDictDto(Dict dict);
    List<DictDto> toDictDto(List<Dict>  dict);

    DictBaseDto toDictBaseDto(Dict dict);
    List<DictBaseDto> toDictBaseDto(List<Dict> dicts);

    Dict toDict(DictCmdAdd cmdAdd);
    Dict toDict(DictCmdUpdate cmdUpdate);
  }

}
